package org.sinuto.documentserver.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
import org.sinuto.documentserver.constant.Error;
import org.sinuto.documentserver.exception.DocumentServerException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileUtils {

    public static void save(MultipartFile file, String path) throws DocumentServerException {
        try {
            IOUtils.copy(file.getInputStream(), new FileOutputStream(path));
        } catch (Exception e) {
            e.printStackTrace();
            throw DocumentServerException.build(Error.FILE_ERROR);
        }
    }

    public static void save(InputStream is, String path) throws DocumentServerException {
        try {
            IOUtils.copy(is, new FileOutputStream(path));
        } catch (Exception e) {
            e.printStackTrace();
            throw DocumentServerException.build(Error.FILE_ERROR);
        }
    }

    /**
     * 前端下载文件方法
     *
     * @param filepath
     * @param response
     * @throws IOException
     */
    public static void getResource(String filepath, String filename, HttpServletResponse response) throws IOException {
        File file = new File(filepath);
        FileInputStream fis = new FileInputStream(file);
        // 清空response
        response.reset();
        // 设置response的Header
        response.setCharacterEncoding(CharEncoding.UTF_8);
        //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
        //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
        // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(filename, CharEncoding.UTF_8));
        // 告知浏览器文件的大小
        response.addHeader(HttpHeaders.CONTENT_LENGTH, "" + file.length());

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
//        outputStream.write(buffer);
        IOUtils.copy(fis, response.getOutputStream());
        fis.close();
        response.getOutputStream().flush();
    }


}
